<template>
  <div class="tab-container">
    <px-form ref="queryRef" class="custom-form-ui-new" :model="queryParams" :inline="true" label-width="68px">
      <px-form-item label="区域" prop="areaCode" style="width: 220px">
        <px-select v-model="queryParams.areaCode" filterable clearable placeholder="请选择区域">
          <px-option v-for="item in areaList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item label="GROUP" prop="group" style="width: 220px">
        <!-- <px-select v-model="queryParams.group" clearable placeholder="请选择GROUP">
          <px-option v-for="item in areaList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select> -->
        <px-input v-model="queryParams.group" clearable />
      </px-form-item>
      <px-form-item label="化滤类型" prop="type" style="width: 220px">
        <px-select v-model="queryParams.type" filterable clearable placeholder="请选择化滤类型">
          <px-option v-for="item in filterList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item label="更换周期" prop="lifecycle" style="width: 220px">
        <px-select v-model="queryParams.lifecycle" filterable clearable placeholder="请选择更换周期">
          <px-option v-for="item in replaceDateList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item label="化滤安装日期" style="width: 460px">
        <px-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </px-form-item>
      <px-form-item>
        <px-button type="primary" @click="getList">查询</px-button>
        <px-button @click="resetQuery">重置</px-button>
      </px-form-item>
    </px-form>

    <div class="btn-con">
      <px-button v-has="'FFU_LEDGER_EXPORT'" type="primary" plain class="btn-item" @click="handleExport">导出</px-button>
    </div>

    <px-table v-loading="loading" :header-cell-style="{ background: '#e7eefb', color: '#000' }" height="calc(100vh - 316px)" border :data="tableList">
      <!-- <px-table-column width="100" label="厂区" align="center" prop="id" /> -->
      <px-table-column label="序号" fixed="left" type="index" width="60">
        <template #default="{ $index }">
          {{ $index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
        </template>
      </px-table-column>
      <px-table-column label="FFU编号" align="center" prop="ffuCode" width="200" />
      <px-table-column label="FFU分组" align="center" prop="ffuGroup" />
      <px-table-column label="设备位号" align="center" prop="ffuId" width="200" />
      <!-- <px-table-column label="FFU分组" align="center" prop="ffuGroup">
        <template #default="scope">
          <px-input
            v-if="data.tableRowEditIndex === scope.$index && data.tableColumnEditIndex == scope.column.id"
            ref="tableRowInputRef"
            v-model="scope.row.ffuGroup"
            @keyup.enter="
              $event => {
                $event.target.blur();
              }
            "
            @blur="onInputTableBlur(scope)"
          />
          <p v-else class="eidt-row-p" @dblclick="dbClickCell(scope)">
            {{ scope.row.ffuGroup }}
          </p>
        </template>
      </px-table-column> -->
      <px-table-column label="化滤编号" align="center" prop="filterCode" width="200">
        <template #default="scope">
          <px-input v-show="scope.$index === editIndex" v-model="scope.row.filterCode" />
          <p v-show="scope.$index !== editIndex" class="eidt-row-p">
            {{ scope.row.filterCode }}
          </p>
          <!-- <px-input
            v-if="data.tableRowEditIndex === scope.$index && data.tableColumnEditIndex == scope.column.id"
            ref="tableRowInputRef"
            v-model="scope.row.filterCode"
            @keyup.enter="
              $event => {
                $event.target.blur();
              }
            "
            @blur="onInputTableBlur(scope, scope.row.filterCode)"
          />
          <p v-else class="eidt-row-p">
            {{ scope.row.filterCode }}
            <px-icon style="margin-left: 5px; cursor: pointer" @click="dbClickCell(scope)"><EditPen /></px-icon>
          </p> -->
        </template>
      </px-table-column>
      <px-table-column label="化滤类型" align="center" prop="filterType">
        <template #default="scope">
          <px-select
            v-show="scope.$index === editIndex"
            v-model="scope.row.filterType"
            filterable
            placeholder="请选择化滤类型"
            @change="changeFn(scope.row)"
          >
            <px-option v-for="item in filterList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
          <p v-show="scope.$index !== editIndex" class="eidt-row-p">
            {{ scope.row.filterType }}
          </p>
        </template>
      </px-table-column>
      <px-table-column label="区域" align="center" prop="area">
        <template #default="scope">
          <px-select v-show="scope.$index === editIndex" v-model="scope.row.area" filterable placeholder="请选择区域" @change="changeFn(scope.row)">
            <px-option v-for="item in areaList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
          <p v-show="scope.$index !== editIndex" class="eidt-row-p">
            {{ scope.row.area }}
          </p>
        </template>
      </px-table-column>
      <px-table-column label="安装位置" align="center" prop="position" />
      <px-table-column label="过滤器更换周期（天）" align="center" prop="lifecycle_exp" width="160">
        <template #default="scope">
          <px-select
            v-show="scope.$index === editIndex"
            v-model="scope.row.lifecycle_exp"
            filterable
            placeholder="请选择更换周期"
            @change="changeFn(scope.row)"
          >
            <px-option v-for="item in replaceDateList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
          <p v-show="scope.$index !== editIndex" class="eidt-row-p">
            {{ scope.row.lifecycle_exp }}
          </p>
        </template>
      </px-table-column>
      <px-table-column label="化滤安装日期" align="center" prop="filterInstallDate" width="180">
        <template #default="scope">
          <div>{{ scope.row.filterInstallDate.split(" ")[0] }}</div>
        </template>
      </px-table-column>
      <px-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template #default="scope">
          <px-tooltip v-if="scope.$index !== editIndex" content="修改" placement="top">
            <px-button v-has="'FFU_LEDGER_EDIT'" link type="primary" icon="Edit" @click="handleEdit(scope.row)" />
          </px-tooltip>
          <px-tooltip v-if="scope.$index === editIndex" content="保存" placement="top">
            <px-button v-has="'FFU_LEDGER_EDIT'" link type="primary" icon="Check" @click="handleComfim(scope.row)" />
          </px-tooltip>
          <px-tooltip v-if="scope.$index === editIndex" content="取消" placement="top">
            <px-button v-has="'FFU_LEDGER_EDIT'" link type="danger" icon="Close" @click="cancelFn" />
          </px-tooltip>
          <px-tooltip v-if="scope.$index !== editIndex" content="复制" placement="top">
            <px-button v-has="'FFU_LEDGER_COPY'" link type="primary" icon="DocumentCopy" @click="handleCopy(scope.row, scope.$index)" />
          </px-tooltip>
          <px-tooltip v-if="scope.$index !== editIndex" content="删除" placement="top">
            <px-button v-has="'FFU_LEDGER_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row, scope.$index)" />
          </px-tooltip>
        </template>
      </px-table-column>
    </px-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "FFULedger"
});
import { PxMessage, PxMessageBox } from "px-ui";
import { getFFUList, ffuAdd, ffuDelete } from "@/api/machineClass";
import { queryChildByTypeCodeAndItemValue, queryDictData } from "@/api/common";
import { getCurrentInstance, onMounted, reactive, ref, toRefs, nextTick } from "vue";

const { proxy }: any = getCurrentInstance();
const areaList = ref([]);
// 获取区域列表
const queryAreaList = async () => {
  areaList.value = [
    {
      value: "",
      label: "FAB"
    }
  ];
  const res: any = await queryChildByTypeCodeAndItemValue({
    typeCode: "FAB_AREA"
  });
  areaList.value.push(
    ...res
      .filter(e => e.itemDesc.includes("FFU"))
      .map(e => {
        return { value: e.itemName, label: e.itemName };
      })
  );
};
const filterList = ref([
  {
    value: "Acid",
    label: "Acid"
  },
  {
    value: "Base",
    label: "Base"
  },
  {
    value: "VOC",
    label: "VOC"
  },
  {
    value: "RC",
    label: "RC"
  }
]);

const replaceDateList = ref([
  {
    value: 120,
    label: "120"
  },
  {
    value: 90,
    label: "90"
  },
  {
    value: 60,
    label: "60"
  },
  {
    value: 30,
    label: "30"
  }
]);

const dateRange = ref([]);
const loading = ref(true);
const ids = ref([]);
const tableRowInputRef: any = ref(null);

const data = reactive<Record<string, any>>({
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  rules: {
    typeName: [{ required: true, message: "字典名称不能为空", trigger: "blur" }],
    typeCode: [{ required: true, message: "字典类型不能为空", trigger: "blur" }]
  },
  tableList: [],
  // 编辑的表格行
  tableRowEditIndex: undefined,
  // 编辑的表格列
  tableColumnEditIndex: undefined,
  total: 0
});

const { queryParams, rules, total, tableList } = toRefs(data);
const classNameArr = ref<any>([]);

const vFocus = {
  mounted: (el: any) => el.querySelector("input").focus()
};

const editIndex = ref(-1);

// 编辑行
const handleEdit = (row: any) => {
  editIndex.value = tableList.value.indexOf(row);
};

// 提交
const handleComfim = async (row: any) => {
  if (!row.filterCode) {
    PxMessage.warning("请输入化滤编号");
    return;
  }
  const res = await ffuAdd(row);
  if (res) {
    editIndex.value = -1;
    PxMessage.success("保存成功");
    getList();
  }
};

// 取消
const cancelFn = () => {
  editIndex.value = -1;
};
// 双击可编辑的单元格
const dbClickCell = (row: any) => {
  // console.log(scope);
  // // 找到单个格子独有的属性 - 这里是用所在行跟列id区别显示
  // data.tableRowEditIndex = scope.$index;
  // data.tableColumnEditIndex = scope.column.id;
  // nextTick(() => {
  //   // 获取焦点
  //   tableRowInputRef.value.focus();
  // });
};

// 表格中input取消焦点,select变化
const onInputTableBlur = (scope: any, val: string) => {
  console.log("取消焦点", scope);
  data.tableRowEditIndex = undefined;
  data.tableColumnEditIndex = undefined;
  const id = scope.row.id;
  const key = scope.column.property;
  const value = scope.row[key];
  // 更新给后端的数据接口
  // 提交数据........
};

const handleCopy = (row: any, index: number) => {
  const newRow = { ...row };
  newRow.filterCode = "";
  newRow.requestId = "";
  tableList.value.splice(index + 1, 0, newRow);
  total.value++;
};

const focusEvent = row => {
  row.oldTypeName = row.typeName;
};

const blurEvent = row => {
  row.isFocus = !row.isFocus;
  // if (row.oldTypeName !== row.typeName) {
  //   ffuAdd(row).then(() => {
  //     getList();
  //   });
  // }
};
const changeFn = row => {
  row.isFocus = !row.isFocus;
};

const cellClick = (row: any, flag) => {
  row.isFocus = !row.isFocus;
};

/** 列表 */
const getList = async () => {
  loading.value = true;
  const res: any = await getFFUList(proxy.addDateRange(queryParams.value, dateRange.value, "installStart", "installEnd")).catch(() => {});
  tableList.value = res?.data.map(item => {
    return {
      ...item,
      oldTypeName: item.typeName,
      isFocus: false
    };
  });
  total.value = res?.total;
  loading.value = false;
};

onMounted(async () => {
  queryAreaList();
  await getList();
  queryDictData({
    type: "class_name"
  }).then((res: any) => {
    classNameArr.value = res ? res.data : [];
  });
});

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  getList();
};

/** 多选框选中数据 */
// const handleSelectionChange = selection => {
//   ids.value = selection.map(item => item.id);
// };

/** 删除按钮操作 */
const handleDelete = (row: any, index: number) => {
  if (row.requestId === "") {
    tableList.value.splice(index, 1);
    total.value--;
  } else {
    PxMessageBox.confirm(`是否确认删除FFU化滤编号为${row.filterCode}的数据项？`, "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    })
      .then(async () => {
        await ffuDelete(row);
        PxMessage.success("删除成功");
        getList();
      })
      .catch(() => {});
  }
};
/** 导出按钮操作 */
const handleExport = () => {
  const params = { ...queryParams.value, installStart: dateRange.value[0], installEnd: dateRange.value[1] };
  params.pageNum = 1;
  params.pageSize = 10000;
  proxy.download("post", "/operation/api/v1/machine/export", params, "FFU台账.xlsx");
};
</script>

<style lang="scss">
.tab-container {
  padding: 16px 24px 0;
}

.custom-form-ui-new {
  margin-bottom: 0;
}

.btn-con {
  display: flex;
  align-items: center;
  justify-content: flex-start;

  .btn-item {
    margin-bottom: 16px;
  }
}

:deep(.pagination-container) {
  margin-top: 6px !important;
  margin-bottom: 6px !important;
}
</style>
